package vinnichenko.lab3.listener;

import vinnichenko.lab3.*;
import vinnichenko.lab3.database.*;
import java.io.*;
import javax.servlet.*;

/**Other packages*/
import org.apache.log4j.Logger;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.PropertyConfigurator;

/**Web context listener.
 * @author Igor Vinnichenko
 * @version 1.0
 */
public final class ContextListener implements ServletContextListener{
    /**Logger*/
    static Logger logger = Logger.getLogger(ContextListener.class);

    /**Context object.*/
    private ServletContext context = null;

    /**Context initialization*/
    public void contextInitialized(ServletContextEvent event){
        /**Get context.*/
        context = event.getServletContext();

        /**String containing log4j properties file name*/
        String log4jLocation = context.getInitParameter("log4j-properties-location");

        /**If it doesn't exist - call basic configurator, or else configure according to properties in file.*/
        if (log4jLocation == null) {
            BasicConfigurator.configure();
        } else {
            String webAppPath = context.getRealPath("/");
            String log4jProp = webAppPath + log4jLocation;

            File propsFile = new File(log4jProp);
            if (propsFile.exists()) {
                PropertyConfigurator.configure(log4jProp);
            } else {
                BasicConfigurator.configure();
            }
        }

        /**Try to create DAO and save it as attribute*/
        try{
            EmployeesDAO eDAO = new EmployeesDAO();
            context.setAttribute("eDB", eDAO);
        }catch(Exception e){
            logger.error("Listener context initialization error." + StackWriter.getFullStackTrace(e));
        }
    }

    /**Context destroying*/
    public void contextDestroyed(ServletContextEvent event){
        /**Get context*/
        context = event.getServletContext();

        /**Get and remove DAO from attributes*/
        EmployeesDAO eDAO = (EmployeesDAO)context.getAttribute("eDB");
        try{
            eDAO.remove();
            context.removeAttribute("eDB");
        }catch(Exception e){
            logger.error("Context listener destroying error.");
        }

        logger.info("Context listener successfully destroyed.");
    }
}